﻿using Aliyun.OSS;
using Aliyun.OSS.Common;
using CatUtils.Utils.Currency;
using System;
using System.IO;

namespace AliCharacter_recognition.Utils.Ali.AliOss
{
    /// <summary>
    /// 参考官方文档：https://help.aliyun.com/document_detail/32088.html?spm=a2c4g.11186623.6.1047.7c2141440Fjw0e
    /// </summary>
    public partial class AliOssTool
    {/// <summary>
     /// 创建OSS Client
     /// </summary>
        public static OssClient OssClientLocal = null;

        /// <summary>
        /// 获取本地缓存的OssClient
        /// </summary>
        /// <param name="Endpoint">传输到哪个服务器，请使用EndPoint寻找相关服务器源</param>
        /// <param name="AccessKeyId">权限控制ID</param>
        /// <param name="AccessKeySecret">权限控制密钥</param>
        /// <returns></returns>
        public static OssClient GetOssClient(string Endpoint, string AccessKeyId, string AccessKeySecret)
        {
            try
            {
                if (OssClientLocal == null)
                    OssClientLocal = new OssClient(Endpoint, AccessKeyId, AccessKeySecret);
            }
            catch (Exception ex)
            {
                PrintLog.E(ex);
            }
            return OssClientLocal;
        }

        /// <summary>
        /// 创建存储空间  失败返回NULL，请做判断。
        /// </summary>
        /// <param name="Endpoint">传输到哪个服务器，请使用EndPoint寻找相关服务器源</param>
        /// <param name="AccessKeyId">权限控制ID</param>
        /// <param name="AccessKeySecret">权限控制密钥</param>
        /// <param name="BucketName">要创建的存储空间名字</param>
        /// <returns></returns>
        public static Bucket CreateBucket(string Endpoint, string AccessKeyId, string AccessKeySecret, string BucketName)
        {
            try
            {
                // 创建OSSClient实例。
                var OssClient = GetOssClient(Endpoint, AccessKeyId, AccessKeySecret);
                if (OssClient == null) { PrintLog.E("初始化Client失败！无法继续操作！"); return null; }
                // 创建存储空间。
                Bucket bucket = OssClient.CreateBucket(BucketName);
                Console.WriteLine("Create bucket succeeded, {0} ", bucket.Name);
                return bucket;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Create bucket failed, {0}", ex.Message);
            }
            return null;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="Endpoint">传输到哪个服务器，请使用EndPoint寻找相关服务器源</param>
        /// <param name="AccessKeyId">权限控制ID</param>
        /// <param name="AccessKeySecret">权限控制密钥</param>
        /// <param name="BucketName">存储空间名字</param>
        /// <param name="ObjectName">上传的对象名</param>
        /// <param name="LocalFileName">本地文件名</param>
        /// <returns></returns>
        public static PutObjectResult UploadFile(string Endpoint, string AccessKeyId, string AccessKeySecret, string BucketName, string ObjectName, string LocalFileName)
        {
            return UploadFile(GetOssClient(Endpoint, AccessKeyId, AccessKeySecret), BucketName, ObjectName, LocalFileName);
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="OssClient">Oss服务</param>
        /// <param name="BucketName">存储空间名字</param>
        /// <param name="ObjectName">上传的对象名</param>
        /// <param name="LocalFileName">本地文件名</param>
        /// <returns></returns>
        public static PutObjectResult UploadFile(OssClient OssClient, string BucketName, string ObjectName, string LocalFileName)
        {
            try
            {
                if (OssClient == null) { PrintLog.E("初始化Client失败！无法继续操作！"); return null; }
                // 上传文件。
                PutObjectResult result = OssClient.PutObject(BucketName, ObjectName, LocalFileName);
              //  Console.WriteLine("Put object succeeded, ETag: {0} ", result.ETag);
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Put object failed, {0}", ex.Message);
            }
            return null;
        }


        /// <summary>
        /// 下载文件辅助
        /// </summary>
        /// <param name="Endpoint">传输到哪个服务器，请使用EndPoint寻找相关服务器源</param>
        /// <param name="AccessKeyId">权限控制ID</param>
        /// <param name="AccessKeySecret">权限控制密钥</param>
        /// <param name="OssClient">Oss服务</param>
        /// <param name="BucketName">存储空间名字</param>
        /// <param name="ObjectName">上传的对象名</param>
        /// <param name="DownloadFileName">下载文件名</param>
        /// <returns></returns>
        public static OssObject DownloadFile(string Endpoint, string AccessKeyId, string AccessKeySecret,
            OssClient OssClient, string BucketName, string ObjectName, string DownloadFileName)
        {
            return DownloadFile(GetOssClient(Endpoint, AccessKeyId, AccessKeySecret), BucketName, ObjectName, DownloadFileName);
        }

        /// <summary>
        /// 下载文件辅助
        /// </summary>
        /// <param name="OssClient">Oss服务</param>
        /// <param name="BucketName">存储空间名字</param>
        /// <param name="ObjectName">上传的对象名</param>
        /// <param name="DownloadFileName">下载文件名</param>
        /// <returns></returns>
        public static OssObject DownloadFile(OssClient OssClient, string BucketName, string ObjectName, string DownloadFileName)
        {
            try
            {
                if (OssClient == null) { PrintLog.E("初始化Client失败！无法继续操作！"); return null; }
                //这一步是先上传再下载相关的文件
                // client.PutObject(BucketName, ObjectName, localFilename);
                // 下载文件。
                OssObject result = OssClient.GetObject(BucketName, ObjectName);
                using (var requestStream = result.Content)
                {
                    using (var fs = File.Open(DownloadFileName, FileMode.OpenOrCreate))
                    {
                        int length = 4 * 1024;
                        var buf = new byte[length];
                        do
                        {
                            length = requestStream.Read(buf, 0, length);
                            fs.Write(buf, 0, length);
                        } while (length != 0);
                    }
                }
                Console.WriteLine("Get object succeeded");
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
            return null;
        }
    }
}